package org.supreme.basic.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.supreme.basic.defaut.Throw;
import org.supreme.basic.dtovo.Smscode;
import org.supreme.basic.excetion.GlobExcetionEnum;
import org.supreme.basic.excetion.GlobalExcetion;
import org.supreme.basic.result.JSONResult;
import org.supreme.basic.service.verifyCodeService;
import org.supreme.basic.util.StrUtils;
import org.supreme.basic.util.VerifyCodeUtils;

import java.util.concurrent.TimeUnit;

@Service
public class verifyCodeServiceImpl implements verifyCodeService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Override
    public JSONResult verifyCode(String imageCodeKey) {
        //生成图形验证码
        String complexRandomString = StrUtils.getComplexRandomString(4);

        //存入到Redis中
        redisTemplate.opsForValue().set(imageCodeKey,complexRandomString,5,TimeUnit.MINUTES);
        //设置大小
        String s = VerifyCodeUtils.verifyCode(115, 40, complexRandomString);
        return JSONResult.success(s);
    }

    @Override
    public JSONResult smscode(Smscode smscode) {
        //判断图形验证码是否存在
        String imagekey = redisTemplate.opsForValue().get(smscode.getImageCodeKey());
        System.out.println(imagekey);
        if (imagekey==null){
            throw new GlobalExcetion(GlobExcetionEnum.COMMON_IMAGECODE_NULL);
        }
        //判断当前的图形验证码与传入的是否一样
        if(!smscode.getImageCode().equalsIgnoreCase(imagekey)){
            throw new GlobalExcetion(GlobExcetionEnum.COMMON_USERCODE_DTO);
        }
        //判断传入的UUID去查询有没有Redis中的数据，如果没有就是第一次获取验证码
        String smskey = smscode.getPhone()+":"+ Throw.REGISTER;
        //从Redis中间拿值
        String smsValue = redisTemplate.opsForValue().get(smskey);
        //判断有没有值
        if (smsValue==null){
            String code1 = StrUtils.getComplexRandomString(4);
            //存入到Redis中间
            redisTemplate.opsForValue().set(smskey,code1+":"+System.currentTimeMillis(),3,TimeUnit.MINUTES);
            System.out.println(code1);

            return JSONResult.success();
        }
        Long valueTime=Long.valueOf(smsValue.split(":")[1]);
        //判断当前的时间减去以前的时间是否大于1，或者是第一次发送短信
        if (System.currentTimeMillis()-valueTime>=1){
            //重新生成验证码
            String code2 = StrUtils.getComplexRandomString(4);
            //存入到Redis中间
            redisTemplate.opsForValue().set(smskey,code2+":"+System.currentTimeMillis(),3,TimeUnit.MINUTES);
            System.out.println(code2);
        }else {
            //如果判断时间没有过一分钟就继续使用以前的，如果重新刷新存入Redis的时间
            String code3=smsValue.split(":")[0];
            redisTemplate.opsForValue().set(smskey,code3+":"+System.currentTimeMillis(),3,TimeUnit.MINUTES);
            System.out.println(code3);
        }

        return JSONResult.success();
    }
}
